<?php
namespace app\client\controller;
class Category extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    //新增分类
    public function add() {
        $name = request()->post('name', '', 'htmlspecialchars');
        $model = model('ChatCategory');
        $rs = $model->findOne(['user_id' => $this->userid, 'name' => $name], 'id');
        if($rs){
            return errorResult('已存在相同名称的分类');
        }
        
        $id = $model->add(['name' => $name, 'user_id' => $this->userid]);
        
        if(!$id){
            return errorResult();
        }
        
        return successResult(['id' => $id]);
       
    }
	
    public function update() {
        $params = request()->post();
        $id = isset($params['id']) ? intval($params['id']) : 0;
        if($id <= 0) {
            return errorResult();
        }
        $name = isset($params['name']) ? htmlspecialchars($params['name']) : '';
        $model = model('ChatCategory');
        $rs = $model->findOne(['id' => $id], ['user_id', 'name']);
        if(empty($rs) || $rs['user_id'] != $this->userid) {
            return errorResult();
        }
        
        if($rs['name'] == $name) {
            return successResult('修改成功');
        }
        
        $rs = $model->modify(['id' => $id], ['name' => $name]);
        if($rs) {
            return successResult('修改成功');
        }else {
            return errorResult();
        }
    }
    
    public function remove() {
        $id = request()->route('id', 0, 'intval');
        if($id <= 0) {
            return errorResult();
        }
        $model = model('ChatCategory');
        $rs = $model->findOne(['id' => $id], ['user_id']);
        if(empty($rs) || $rs['user_id'] != $this->userid) {
            return errorResult();
        }
        
        $rs = $model->where(['id' => $id])->delete();
        if($rs) {
            return successResult('删除成功');
        }else {
            return errorResult();
        }
    }
    
	public function categorys() {
	    $storeId = request()->get('storeId', 0, 'intval');
	    $where['user_id'] = $storeId > 0 ? $storeId : $this->userid;
	    $list = model('ChatCategory')->findAll($where, ['id', 'name', 'count']);
		return successResult(['list' => $list]);
	}
}